<?php
/**
 * $Id: parser.php 21 2009-06-10 02:24:31Z eyou80 $
 */

/**
 * 路由解析器
 *
 * @package Router
 */
class Tinyask_Router_Parser
{

	/**
	 * 匹配规则
	 *
	 * @var array
	 */
	private $_regx;

	/**
	 * 路由配置信息
	 *
	 * @var array
	 */
	private $_routes;

	/**
	 * 参数
	 *
	 * @var array
	 */
	private $_params;

	/**
	 * 设置路由配置信息
	 *
	 * @param array $routes
	 */
	public function __construct(array $routes)
	{
		$this->_routes = $routes;

		$this->_regx = array(
			'string' => '(.%s)',
			'char' => '([^/]%s)',
			'digital' => '([0-9]%s)',
			'alpha' => '([_0-9a-zA-Z-]%s)',
			'alphaslash' => '([_0-9a-zA-Z-/]%s)'
		);
	}

	/**
	 * 解析路由表
	 *
	 * @return array
	 */
	public function parse()
	{
		$routes = array();

		foreach ($this->_routes as $key => $route) {
			$this->_params = array();
			$route['regx'] = preg_replace_callback("/%(^%)+%/", array($this, '_match'),
			preg_quote(str_replace(array('[', ']', ':'), array('%', '%', ' '), $route['url'])));

			$route['regx'] = rtrim($route['regx'], '/');
			$route['regx'] = '|^' . $route['regx'] . '[/]?$|';

			$route['format'] = preg_replace("/\[([^\]]+)\]/", "%s", $route['url']);
			$route['params'] = $this->_params;

			$routes[$key] = $route;
		}

		return $routes;
	}

	/**
	 * 字符串路由信息匹配
	 *
	 * @param array $matches
	 * @return string
	 */
	public function _match(array $matches)
	{
		$params = explode(' ', $matches[1]);
		$paramsNum = count($params);
		$this->_params[] = $params[0];

		switch ($paramsNum) {
			case 1:
				return sprintf($this->_regx['char'], '+');
			case 2:
				return sprintf($this->_regx[$params[1]], '+');
			case 3:
				return sprintf($this->_regx[$params[1]], '{' . $params[2] . ',}');
			case 4:
				return sprintf($this->_regx[$params[1]], '{' . $params[2] . ',' . $params[3] . '}');
		}
	}
}
